<?php

namespace App\Http\Middleware;


use App\Exceptions\SignException;
use App\Models\User;
use Closure;

//TODO 这里没写正常的oauth2 token鉴权，下个版本再优化  用jwt
class Authenticate
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws SignException
     */
    public function handle($request, Closure $next)
    {
        $apiKey = env('API_KEY');

        $token = $request->input('token', -1);

        $time = $request->input('time', -1);

        $key = $request->input('key', -1);

        if(time() - $time > 60 * 2){ //判断请求超时
            throw new SignException();
        }

        // 获取用户token
        $user = User::where('openid', $key)->first();

        if (filled($user)) {
            if (md5($user->openid . $apiKey . (string)$time) == $token) {
                define('UID', $user->id);
                return $next($request);
            }
        }

        throw new SignException();
    }
}
